package petstore.web.servlet.search;

import com.alibaba.fastjson.JSON;
import petstore.domain.Product;
import petstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/autoComplete")
public class AutoCompleteServlet extends HttpServlet {
    private String searchString;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        searchString = req.getParameter("searchString");
        //System.out.println(searchString);
        CatalogService catalogService = new CatalogService();//实例化一个CatalogService对象
        List<Product> searchResult = catalogService.getProductListByName(searchString);

        String json = JSON.toJSONString(searchResult);
        //System.out.println(json);//转换为json
        resp.setContentType("text/Json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
